import { useAudioPlay } from "@/hooks/useAudioPlay";
import { useState, useRef, useCallback, useEffect } from "react";

interface ItemReadProps {
  value: string;
  isPlay?: boolean;
  readText?: string;
}

const ItemRead: React.FC<ItemReadProps> = ({ value, isPlay = false, readText = '' }) => {
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
  const { isPlaying, isLoading, playAudio, stopAudio } = useAudioPlay({});
  const words = value.split(" ");

  const handleWordClick = useCallback((word: string, index: number) => {
    
    // 清除之前的定时器
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    
    // 设置高亮索引
    setHighlightedIndex(index);
  
    // 触发发音
    playAudio(word).then(() => {
      // 发音结束后，设置一个延迟再取消高亮
      timeoutRef.current = setTimeout(() => {
        setHighlightedIndex(-1);
      }, 800);
    }).catch(() => {
      // 如果发音失败，也延迟取消高亮
      timeoutRef.current = setTimeout(() => {
        setHighlightedIndex(-1);
      }, 800);
    });
  }, [playAudio]);

  // 自动高亮效果
  useEffect(() => {
    if (isPlay && words.length > 0 &&readText==value) {
      setHighlightedIndex(0);
      
      const interval = setInterval(() => {
        setHighlightedIndex(prevIndex => {
          const nextIndex = prevIndex + 1;
          if (nextIndex >= words.length) {
            clearInterval(interval);
            return -1;
          }
          return nextIndex;
        });
      }, 500);
      
      return () => {
        clearInterval(interval);
        setHighlightedIndex(-1);
      };
    }
  }, [isPlay, words.length]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);


  return (
    <>
      {words.length > 0 ? (
        words.map((word: string, index) => {
          const isHighlighted = index === highlightedIndex;
          return (
            <div
              key={index}
              style={{
                backgroundColor: isHighlighted ? '#4a6cf7' : 'transparent',
                color: isHighlighted ? 'white' : 'inherit',
                display: 'inline-block',
                cursor: 'pointer',
                padding: isHighlighted ? '4px 8px' : '2px 4px',
                borderRadius: isHighlighted ? '8px' : '3px',
                transition: 'all 0.3s ease',
                transform: isHighlighted ? 'scale(1.05)' : 'scale(1)',
                boxShadow: isHighlighted ? '0 4px 8px rgba(74, 108, 247, 0.3)' : 'none',
              }}
              onClick={() => handleWordClick(word,index)}
            >
              {word.trim()}
            </div>
          );
        })
      ) : (
        <div>{value}</div>
      )}
    </>
  );
};

export default ItemRead;